﻿﻿/**
 * Created by TX on 2016/9/27
 * version: 3.0.4
 */
console.log("UC say hello ");


(function (global, factory) {
    typeof exports === 'object' && typeof module !== 'undefined' ? module.exports = factory() :
        typeof define === 'function' && define.amd ? define( ["jquery"], factory):
            (global.AgentBar = factory());
}(this, function () {

    var config = {
        //DeBug 打印级别
        DeBug: true,
        //初始化地址
        proxyUrl: ""
    }

    /***返回数据封装***/
    var callbackdata = {
        Result:'0',
        Code:'0',
        EventType:null,  //座席登录事件
        CallDetailEvent:null,  //话务呼叫事件
        OrgANI:null,
        OrgDNIS:null,
        ANI:null,
        DNIS:null,
        CslANI:null,
        CslDNIS:null,
        ServiceType:null,
        OrgReqSkill:null,
        ResSkill:null,
        CallType:null,
        SessionID:null,
        IVRData:null,
        bIsInfo:null,
        strDestAgentID:null,
        AgentMessage:null
    };


    /************************操作类型 Start************************/

    var operation_type = new Array();
// 外呼
    operation_type[0] = "CallOut";
// 置闲
    operation_type[1] = "Ready";
// 置忙
    operation_type[2] = "NotReady";
// 挂断
    operation_type[3] = "Disconnect";
// 坐席协作
    operation_type[4] = "Cooperation";
// 接回
    operation_type[5] = "Retrive";

    /************************操作类型 End************************/

    /************************参数列表 Start************************/
    var call_in_params = new Array();
// 原始主叫
    call_in_params[0] = "OrgANI";
// 原始被叫
    call_in_params[1] = "OrgDNIS";
// 当前主叫
    call_in_params[2] = "ANI";
// 当前被叫
    call_in_params[3] = "DNIS";
// 咨询主叫
    call_in_params[4] = "CslANI";
// 咨询被叫
    call_in_params[5] = "CslDNIS";
// 服务类型
    call_in_params[6] = "ServiceUnitType";
// 请求技能组
    call_in_params[7] = "ReqSkill";
// 响应技能组
    call_in_params[8] = "ResSkill";
// 呼叫类型
    call_in_params[9] = "CallType";
// 本次呼叫标识
    call_in_params[10] = "SessionID";
// IVR数据
    call_in_params[11] = "IVRData";

    /************************参数列表 End************************/

    var prefix = "";

    var handle;

    /**********************返回结果定义 Start************************/

// 事件类型
    var EventType = "EventType";
// 原始主叫
    var OrgANI = "OrgANI";
// 原始被叫
    var OrgDNIS = "OrgDNIS";
// 当前主叫
    var ANI = "ANI";
// 当前被叫
    var DNIS = "DNIS";
// 咨询主叫
    var CslANI = "CslANI";
// 咨询被叫
    var CslDNIS = "CslDNIS";
// 服务类型
    var ServiceUnitType = "ServiceUnitType";
// 请求技能组
    var ReqSkill = "ReqSkill";
// 响应技能组
    var ResSkill = "ResSkill";
// 呼叫类型
    var CallType = "CallType";
// IVR数据
    var IVRData = "IVRData";
// 本次呼叫表示
    var SessionID = "SessionID";
// 坐席工号
    var agentID = "";
// 坐席分机
    var deviceID = "";
// 是否首次登录
    var isFirstLogin = false;


    /**********************返回结果定义 End************************/

    /**********************事件类型EventType Start************************/

// Init状态
    var AgentStatus_Init = "AgentStatus_Init";
// Login状态
    var AgentStatus_Login = "AgentStatus_Login";
// Logout状态
    var AgentStatus_Logout = "AgentStatus_Logout";
// Ready状态
    var AgentStatus_Ready = "AgentStatus_Ready";
// NotReady状态
    var AgentStatus_NotReady = "AgentStatus_NotReady";
// Otherwork状态
    var AgentStatus_Otherwork = "AgentStatus_Otherwork";
// ACW状态
    var AgentStatus_ACW = "AgentStatus_ACW";
// Locked状态
    var AgentStatus_Locked = "AgentStatus_Locked";
// Alerting状态
    var AgentStatus_Alerting = "AgentStatus_Alerting";
// Connecting状态
    var AgentStatus_Connecting = "AgentStatus_Connecting";
// Connected_Normal状态
    var AgentStatus_Connected_Normal = "AgentStatus_Connected_Normal";
// Connected_Internal状态
    var AgentStatus_Connected_Internal = "AgentStatus_Connected_Internal";
// Disconnected状态
    var AgentStatus_Disconnected = "AgentStatus_Disconnected";
// Suspended状态
    var AgentStatus_Suspended = "AgentStatus_Suspended";
// Held状态(请求IVR服务时转为此状态)
    var AgentStatus_Held = "AgentStatus_Held";
// Consulting状态
    var AgentStatus_Consulting = "AgentStatus_Consulting";
// Consulted状态
    var AgentStatus_Consulted = "AgentStatus_Consulted";
// Conferenced状态
    var AgentStatus_Conferenced = "AgentStatus_Conferenced";
// Monitored状态
    var AgentStatus_Monitored = "AgentStatus_Monitored";
// Inserted状态
    var AgentStatus_Inserted = "AgentStatus_Inserted";
// Unkown状态
    var AgentStatus_Unkown = "AgentStatus_Unkown";

    /**********************事件类型EventType End************************/

    /**********************呼叫类型 Start************************/

// 呼叫类型：
// 标识 信息 信息描述
// 0 INTERNAL 呼入
// 1 OUTBOUND 外呼
// 2 INBOUND 内呼
    var INTERNAL = "INTERNAL";
    var OUTBOUND = "OUTBOUND";
    var INBOUND = "INBOUND";

    var event_params = new Array();
// 原始主叫
    event_params[0] = OrgANI;
// 原始被叫
    event_params[1] = OrgDNIS;
// 当前主叫
    event_params[2] = ANI;
// 当前被叫
    event_params[3] = DNIS;
// 咨询主叫
    event_params[4] = CslANI;
// 咨询被叫
    event_params[5] = CslDNIS;
// 服务类型
    event_params[6] = ServiceUnitType;
// 请求技能组
    event_params[7] = ReqSkill;
// 响应技能组
    event_params[8] = ResSkill;
// 呼叫类型
    event_params[9] = CallType;
// 本次呼叫标识
    event_params[10] = SessionID;
// IVR数据
    event_params[11] = IVRData;

    /**********************呼叫类型 End************************/




    var DEST_TYPE_INTERDN = 1; // 分机
    var DEST_TYPE_EXTERDN = 3; // 外线

    var SET_AUTO_READY = false;	// 是否自动示闲

    /**
     * 座席端相关配置
     */
    var option = {
        agentId: "",//座席工号
        agentDn: "", //座席分机
        agentName: "",//座席昵称
        agentType: 5,//座席类型
        acdAgentPassword:'',//座席密码
        agentDnPwd : '',//分机密码
        proxyUrl: '',//坐席代理地址，http://host:port
        wsUrl: '',//ws地址
        udpUrl: '',//sip地址
        iceServers: '',//ice服务
        autoRTCAnswer: false,//RTC 自动应答
        debug:true,
        entId:''
    };

    var ucwindows;
    var ucdocument;
    var handle;
    var client;
    //uc入口
    function UCObj(win, doc) {

        ucwindows = win;
        ucdocument = doc;

        this.exportCallBackData = function(){};
        this.initUCObj = function (agentId,agentPwd, EnterpriseID,agentDn,agentName,agentType,skillDesc,proxyUrl,agentDnPwd,serverUrl,wsUrl,udpUrl,stunServers) {

            if(proxyUrl!=null&&proxyUrl!=''){

                option.proxyUrl =proxyUrl;
            }
            option.agentId = agentId;

            option.agentDn = agentDn;
            option.agentName = agentName;
            option.skillDesc = skillDesc;
            option.acdAgentPassword = agentPwd;
            option.entId = EnterpriseID;
            option.agentType = agentType;

           client = new webAgent();
            // var agentDnPwd = '1234'
            // var serverUrl = '62.234.92.196';
            // var wsUrl = '62.234.92.196:21000';
            // var udpUrl = '62.234.92.196:35065';
            // var stunServers = '221.194.132.82:61057';
            option.agentDnPwd = agentDnPwd;
            option.serverUrl = serverUrl;
            option.wsUrl = wsUrl;
            option.udpUrl = udpUrl;
            option.stunServers = stunServers;

            client.initialize(option)

            client.start();

            getBarEvent.call(this,client);
            getResponse.call(this,client);

        }

        this.getOption = function(field) {
            return client.getOption(field);
        };

        this.setOption = function(option) {
            return client.setOption(option);
        };

        this.start = function (callback_event) {

            var that = this;
            this.exportCallBackData = callback_event;

            /*            handle = win.setInterval(function () {

             }, config.QueryTime);*/

        };

        this.stopObj = function () {
            clearInterval(handle);
            client.stop();
        }

        /***座席签入**/
        this.loginex = function (callback) {

            var rtn = client.login();
            console.log(rtn)
            var data = callbackdata;
            data.EventType = "AgentStatus_Login";
            isFirstLogin = true;
            callback(data);
        }

        /*
         * 登出处理
         */
        this.doLogOut = function (callback) {

            var rtn =  client.logout();
            var data = callbackdata;
            data.EventType = "AgentStatus_Logout";
            data.AgentMessage = "座席登出成功";
            callback(data);
        }

        /*
         * 置忙处理
         */
        this.doNotReady = function() {
            var rtn =   client.notReady();
        };

        /*
         * 置闲处理
         */
        this.doReady = function() {
            var rtn =   client.ready();
        };

        var sessionId = '';

        /*
         * 发送按键
         */
        this.SendDTMF = function (num) {

            num = num == "#" ? "%23" : num;
            // if (callback != undefined) {
            //
            //     callback(num)
            // }
            console.log('uc.js----sendTMF', sessionId)
            if(null!=sessionId && sessionId!=''){
                console.log('uc.js---SendDTMF', num)
                client.sendDTMF(num);
            }

        };

        /*
         * 接听按键
         */
        this.doAnswer = function () {
            console.log('调用uc.js的doAnswer')
            var rtn =   client.doAnswer();

        }



        /*
         * 外呼处理
         */
        this.doCallOut = function (callNum, showNum) {
            var destType = getDestType(callNum);

/*            if (callNum.length == 12 && callNum.indexOf("01") == 0) {
            	callNum = callNum.substring(1);
            }

            // 外拨号码前需加Sip:的前缀
            if (callNum.length == 4) {
            	callNum = encodeURI("sip:" + callNum);
            } else {

            //	// 外拨号码前需加Tel:的前缀
            	if (callNum.indexOf("Tel:") == -1) {
            		callNum = "Tel:" + callNum;
            }
            }*/
            //外拨加Tel，或出局需加0
            if (callNum.length == 11 || callNum.length == 12) {
                    callNum = "Tel:" + callNum;
            } else {
                callNum = "sip:" + callNum;
            }

            var rtn =  client.makeCall(destType,callNum, showNum);
            if(!rtn){
                alert("执行外呼失败");
                return;
            }

        }

        /**
         * 外呼目标类型（1：分机，2：工号，3：外线）
         * @param destDesc
         * @returns {number}
         */
        function getDestType(destDesc) {

            var destType = 3;

            if (destDesc && destDesc.length <= 6 && destDesc.substring(0, 1) != '0' &&
                destDesc.substring(0, 1) != '1' && destDesc.substring(0, 1) != '9') {
                destType = DEST_TYPE_INTERDN;
            }

            return destType;
        }

        /*
         * 挂断处理
         */
        this.doDisconnect = function () {

            var rtn = client.doHangup();

            if(!rtn){
                alert("执行挂机失败");
                return;
            }
        }

        /*
         * 保持处理
         */
        this.doHold = function () {

            var rtn =   client.doHold();
        }

        /*
         * 接回处理
         */
        this.doRetrive = function () {

            var rtn =   client.doRetrive();

        }


        /*
         *咨询处理  三方通话前外呼 内线座席和外线号码
         */
        this.doConsulting = function (consultType, targetNum) {

            client.doConsulting(consultType, targetNum,sessionId);
        }

        /**
         * 咨询接回
         */
        this.reconnectCall = function() {
            client.reconnectCall();
        }
        /*
         *转接
         *
         */
        this.doAdressShift = function () {

            client.doAdressShift();
        }

        /*
         * 三方通话  doThreeCall  话务条用会议按钮
         */
        this.doMeeting = function(){

            _showMessage.showDebugMessage("doMeeting:");

            client.doMeeting();
        }


        /**
         * 自动示闲按钮 挂断电话后
         * @param autoReady
         */
        this.setAutoReady = function (autoReady){

            SET_AUTO_READY = autoReady;
        }

        /*
         * 坐席转IVR接口
         */
        this.doTransferIVR = function () {

            _showMessage.showDebugMessage("doAssistIVRServicer:");
            client.doTransferIVR("");
        }

        /**
         * 座席协作
         * @param dataKey
         * @param dataValue
         */
        this.doAssistService = function (dataKey, dataValue){
            client.doAssistService(dataKey, dataValue);
        }
        /**
         * 单步 转接 会议
         * @param consultType 1 内线 2-外线
         * @param destType  1-转接 2-会议
         * @param targetNum 目标号码
         */
        this.doSingleStep = function (consultType,destId, targetNum){

            client.doSingleStep(consultType,destId,targetNum,sessionId)
        }
        /**
         * 密语
         * @param sessionId
         * @param destType
         */
        this.doWhisper= function (destType,callback){
            client.whisper(sessionId,destType);
            client.onWhisperData = function(data) {
                callback(data)
            }
        }

        /*
        * 监听处理
        */
        this.doListen = function (conferenceParty) {

            client.doListen(conferenceParty);
        }
        /*
       *强插处理
       */
        this.doInsert = function () {
            client.doInsert()
        }
        /*
        * 强拆处理
        */
        this.doDrop = function (destAgentId) {

            client.doDrop(destAgentId)
        }

        /*
         * 获取坐席状态
         */
        this.GetAgentState = function(agentId,callback){

            var arr = {};
            var that = this;
            _showMessage.showDebugMessage(agentId);
            var status = that.getOption('status');
            _showMessage.showDebugMessage("status:"+status)
            client.getAgentState(agentId);
            if(status==-1||status==7){
                arr = {"Code":"0","IsLogon":false};
                callback(arr);

            }else{
                var sessionId = that.getOption('sessionId');
                var IVRData;
                client.getAgentState(agentId);
                var AgentStatus;
                client.onAgentState = function(data) {
                    status = data;
                    switch(status){
                        case -1: //初始化
                            AgentStatus = "AgentStatus_Init";
                            break;
                        case 0: //签入
                            AgentStatus = "AgentStatus_Login";
                            break;
                        case 3: //忙碌
                            AgentStatus = "AgentStatus_NotReady";
                            break;
                        case 1: //空闲
                            AgentStatus = "AgentStatus_Ready";
                            break;
                        case 2: //工作
                            AgentStatus = "AgentStatus_Ready";
                            break;
                        case 5: //锁定
                            AgentStatus = "AgentStatus_Locked";
                            break;
                        case 6: //事后整理
                            AgentStatus = "AgentStatus_ACW";
                            break;
                        case 7: //签出
                            AgentStatus = "AgentStatus_Logout";
                            break;
                        case 28: //通话
                            AgentStatus = "AgentStatus_Connected_Normal";
                            break;
                        case 4: //振铃
                            AgentStatus = "AgentStatus_Alerting";

                            //IVRData = that.getCallData("pwdstatus");
                           // console.log("IVRData="+IVRData);
                            break;
                        // case 24: //被咨询振铃
                        //     AgentStatus = "AgentStatus_Consulting";
                        //     break;
                        // case 25: //外拨振铃
                        //     AgentStatus = "AgentStatus_Connecting";
                        //     break;
                        // case 27: //咨询振铃
                        //     AgentStatus = "AgentStatus_Consulting";
                        //     break;
                        // case 29: //保持
                        //     AgentStatus = "AgentStatus_Suspended";
                        //     break;
                        // case 31: //咨询通话
                        //     AgentStatus = "AgentStatus_Consulted";
                        //     break;
                        // case 32: //被咨询通话
                        //     AgentStatus = "AgentStatus_Consulted";
                        //     break;
                        // case 33: //会议
                        //     AgentStatus = "AgentStatus_Conferenced";
                        //     break;
                        // case 34: //被会议
                        //     AgentStatus = "AgentStatus_Conferenced";
                        //     break;
                        default:
                            break;
                    }
                }

                var data = callbackdata;
                data.EventType = AgentStatus;
                data.IVRData = IVRData;
                arr = {"Code":"0","IsLogon":true,"AgentId":agentId,"AgentName":agentId,"EntId":'',"agentDN":agentId,"AgentStatus":AgentStatus,
                    "AgentStateTime":"","CallNumber":"","ConsultNum":"","ListenNumber":"","SessionId":sessionId,"Event":data};
                callback(arr);

            }

        }

        /**
         * 获取座席列表 （获取人员列表）
         * @param showType //0 咨询 2监听 3单步
         * @param callback
         */
        this.doGetAgent = function (showType, callback) {
            console.log('点击获取 agentList----', showType)
            client.getAgentListData(showType);
            client.onAgentListData = function(data) {
                var totalAgent = "";
                for(var i = 0 ; i < data.length ; i ++){

                    totalAgent += data[i].agentId+":"+'座席列表'+";:"+data[i].agentName+"::"+data[i].dn+"|";
                }
                if(totalAgent.length > 0){

                    totalAgent = totalAgent.substr(0,totalAgent.length - 1);
                }
                callback({Code: '0',Msg:totalAgent})
            }
        };

        /**
         * 重置
         * @param callback
         */
        this.doReset = function () {

            var agentId = client.getOption('agentId');
            // client.agentStateReset(1);
            client.agentStateReset(3);

        };
        /*
         * 获取坐席登录信息
         */
        this.doGetShowANI = function (callback) {
            var callData = {};

            client.getAgentDialCaller();
            client.onAgentDialCallerData = function(data) {
                if(null!=data){

                    callData = {Code: '0',Msg:new String(data)};
                    callback(callData)
                }else{
                    callData = {Code: '0',Msg:{Result:-1}}
                    callback(callData)
                }
            }

        }

        /**
         * 获取随路数据
         * @param dataKey
         * @param callback
         */
        this.doGetCallData = function (dataKey,callback){

            client.getCallData(sessionId,dataKey);
            client.onGetCallData = function(data) {
                callback(data)
            }
        }
        /**
         * 设置随路数据
         * @param dataKey
         * @param dataValue
         */
        this.doSetCallData = function (dataKey,dataValue){

            client.setCallData(sessionId,dataKey,dataValue);
        }

        /**
         * 开始静音
         */
        this.doStartMute = function (){

            client.doStartMute();
        }

        /**
         * 结束静音
         */
        this.doStopMute = function (){

            client.doStopMute();
        }

        /****************************************************座席事件*********************************************************/


        function  getBarEvent(client){
            var that = this;

            client.onEvent = function(event) {
                console.log('uc-----接收的事件----', event)
                //首次登录后，置闲后自动置忙----要判断从是否从登录页过来
                if(event.EventType === 'AgentStatus_Ready' && isFirstLogin) {
                    isFirstLogin = false;
                    if(window.phone) {
                        if(phone.config.autoReadyKey && phone.config.autoReadyKey === 'autoReady') {
                            console.log('登录后设置置闲')
                        }
                    } else {
                        console.log('2000---000-')
                        setTimeout(() => {
                            console.log('2000----', client, client.notReady)
                            client.notReady();
                        }, 2000);
                    }
                }
                // 处理来电的电话参数
                var ani = event.ANI;
                if (ani != undefined && ani.toUpperCase().indexOf("TEL:") > -1) {
                    ani = ani.substring(4);
                }
                event.ANI = ani;
                // 外呼本方振铃时，自动接听-外呼
                if(event.EventType === 'AgentStatus_Alerting' && event.CallDetailEvent ==='CA_CALL_EVENT_OUTBOUND_ALERTING_TP') {
                    client.doAnswer();
                    sessionId = event.SessionID.split(":")[0];
                }
                if(event.EventType === 'AgentStatus_Connecting' && event.CallDetailEvent === 'CA_CALL_EVENT_OUTBOUND_ALERTING_OP'){
                    sessionId = event.SessionID.split(":")[0];
                }
                // 处理弹屏事件 内呼
                if(event.EventType === 'AgentStatus_Alerting' && event.CallDetailEvent ==='CA_CALL_EVENT_ALERTING'){
                    sessionId = event.SessionID.split(":")[0];
                }
                // 咨询振铃弹屏处理
                if(event.EventType === 'AgentStatus_Alerting' && event.CallDetailEvent ==='CA_CALL_EVENT_CONSULT_ALERTING_TP') {
                    sessionId = event.SessionID.split(":")[0];
                }
                //挂断后自动示忙
                if(event.EventType === 'AgentStatus_Disconnected' && event.CallDetailEvent ==='CA_CALL_EVENT_TP_DISCONNECT') {
                    sessionId = '';
                    //client.notReady();
                }
                //退出停止服务
                if(event.EventType === 'AgentStatus_Logout') {
                    sessionId = '';
                    client.stop();
                }
                console.log('usjs---中回调接收的参数---', event)
                that.exportCallBackData(event);
            }


        }

        function getResponse(client) {
            var that = this;

            client.onResponseMessage = function(event) {
                console.log('uc接受 各种响应 , ------', event)
                if (event.MessageID == 'Resp_IContact_AgentLogin' || event.MessageID == 'Evt_AgentStatus_Unkown') {
                    that.exportCallBackData(event);
                } else if (event.MessageID == 'Resp_IContact_ConsultCall') {
                    console.log('点击咨询外呼', event)
                    that.exportCallBackData(event);
                }
            }
        }


    }

//控制台输出信息
    function showMessage() {
        //打印接口调用情况
        this.showDebugMessage = function (msg) {
            if (config.DeBug) {
                console.log(msg, "       --From uc Log  ");
            }
        }
    }
    var _showMessage = new showMessage();

    AgentBar = UCObj;
    return AgentBar;

}))